package com.d3works.csv.script;

import com.d3works.apps.account.db.Invoice;
import com.d3works.apps.account.db.repo.InvoiceRepository;
import com.d3works.apps.account.service.invoice.InvoiceService;
import com.d3works.apps.account.service.invoice.InvoiceTermService;
import com.d3works.apps.base.service.AddressService;
import com.d3works.exception.D3worksException;
import com.google.inject.persist.Transactional;
import java.util.Map;
import javax.inject.Inject;

public class ImportInvoice {

  @Inject private AddressService addressService;

  @Inject private InvoiceService invoiceService;

  @Inject private InvoiceRepository invoiceRepo;

  @Inject private InvoiceTermService invoiceTermService;

  @Transactional(rollbackOn = {Exception.class})
  public Object importInvoice(Object bean, Map<String, Object> values) throws D3worksException {
    assert bean instanceof Invoice;
    Invoice invoice = (Invoice) bean;

    if (invoice.getAddress() != null) {
      invoice.setAddressStr(addressService.computeAddressStr(invoice.getAddress()));
    }
    invoiceRepo.save(invoice);
    if (invoice.getStatusSelect() == InvoiceRepository.STATUS_DRAFT) {
      invoiceService.setDraftSequence(invoice);
    }
    if (invoice.getStatusSelect() < InvoiceRepository.STATUS_VENTILATED
        && invoice.getPaymentMode() != null
        && invoice.getInTaxTotal() != null
        && !invoiceTermService.checkIfCustomizedInvoiceTerms(invoice)) {
      invoice = invoiceTermService.computeInvoiceTerms(invoice);
    }

    return invoice;
  }
}
